/**
 *
 */
package com.honeybees.framework.common.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.codec.binary.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <dl>
 * <dt><b> 信息编码 </b></dt>
 * <p>
 * <dd>功能描述</dd>
 * </dl>
 * <p>
 * Copyright (C) All rights reserved.
 * </p>
 *
 * @author 李远明
 * @since 2015年12月30日 下午1:19:30
 */
public class Encoder {

    private static Logger logger = LoggerFactory.getLogger(Encoder.class);

    private static MessageDigest shaDigist = null;
    private static MessageDigest md5Digist = null;

    private Encoder() {
    }

    public static String encode(String src, String dynamicSolt, String staticSolt) {
        String input1 = dynamicSolt + src + staticSolt;
        String first = shaEncode(input1);

        String input2 = first + staticSolt + dynamicSolt;
        return md5Encode(input2);
    }

    private static synchronized String shaEncode(String input) {
        if (input != null && input.length() != 0) {
            getSha256Digist().update(input.getBytes());
            byte[] bytes = getSha256Digist().digest();
            return (new String(Hex.encodeHex(bytes)));
        } else {
            return null;
        }
    }

    private static synchronized String md5Encode(String input) {
        if (input != null && input.length() != 0) {
            getMD5Digist().update(input.getBytes());
            byte[] bytes = getMD5Digist().digest();
            return (new String(Hex.encodeHex(bytes)));
        } else {
            return null;
        }
    }

    private static MessageDigest getSha256Digist() {
        if (shaDigist == null) {
            try {
                shaDigist = MessageDigest.getInstance("SHA-256");
            } catch (NoSuchAlgorithmException e) {
                // e.printStackTrace();
                logger.error("getSha256Digist error", e.getMessage());
            }
        }
        return shaDigist;
    }

    private static MessageDigest getMD5Digist() {
        if (md5Digist == null) {
            try {
                md5Digist = MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException e) {
                // var1.printStackTrace();
                logger.error("getMD5Digist error", e.getMessage());
            }
        }
        return md5Digist;
    }

    public static void main(String[] args) {
        String id = "000109";
        String chromeAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36";
        // String key = Constants.KEY_COOKIE_ENCRYPT_KEY;
        String key = "bfa6026a858e4d3eb9192856ee624590";

        String txt = encode(id, chromeAgent, key);
        System.out.println(txt);
    }

}
